package com.mm.cloth.manager;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.mm.cloth.model.TaskStatus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class TaskStatusManager {
    private static final String TAG = "TaskStatusManager";
    private static TaskStatusManager instance;
    
    private final List<TaskStatus> tasks;
    private final List<TaskStatusListener> listeners;
    private final Handler mainHandler;
    
    public interface TaskStatusListener {
        void onTaskAdded(TaskStatus task);
        void onTaskUpdated(TaskStatus task);
        void onTaskCompleted(TaskStatus task);
        void onTaskFailed(TaskStatus task);
    }
    
    private TaskStatusManager() {
        tasks = new CopyOnWriteArrayList<>();
        listeners = new CopyOnWriteArrayList<>();
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    public static synchronized TaskStatusManager getInstance() {
        if (instance == null) {
            instance = new TaskStatusManager();
        }
        return instance;
    }
    
    public void addListener(TaskStatusListener listener) {
        listeners.add(listener);
    }
    
    public void removeListener(TaskStatusListener listener) {
        listeners.remove(listener);
    }
    
    public String submitTask(TaskStatus.TaskType taskType, String imagePath) {
        TaskStatus task = new TaskStatus(taskType, imagePath);
        tasks.add(0, task); // 添加到列表开头
        
        Log.d(TAG, "提交任务: " + taskType.getDisplayName() + " ID: " + task.getTaskId());
        
        // 通知监听器
        mainHandler.post(() -> {
            for (TaskStatusListener listener : listeners) {
                listener.onTaskAdded(task);
            }
        });
        
        // 开始模拟处理（实际项目中这里应该调用真实API）
        startMockProcessing(task);
        
        return task.getTaskId();
    }
    
    private void startMockProcessing(TaskStatus task) {
        new Thread(() -> {
            try {
                // 开始处理
                task.setStatus(TaskStatus.Status.PROCESSING);
                updateTask(task);
                
                // 模拟进度更新
                for (int progress = 10; progress <= 100; progress += 10) {
                    Thread.sleep(800); // 每0.8秒更新一次进度
                    task.setProgress(progress);
                    
                    // 更新描述
                    if (progress < 30) {
                        task.setDescription("正在上传图片...");
                    } else if (progress < 60) {
                        task.setDescription("AI正在分析图片...");
                    } else if (progress < 90) {
                        task.setDescription("正在生成结果...");
                    } else {
                        task.setDescription("即将完成...");
                    }
                    
                    updateTask(task);
                }
                
                // 处理完成
                task.setStatus(TaskStatus.Status.COMPLETED);
                task.setDescription("处理完成！");
                task.setResultImagePath("result_" + task.getTaskId() + ".jpg");
                
                mainHandler.post(() -> {
                    for (TaskStatusListener listener : listeners) {
                        listener.onTaskCompleted(task);
                    }
                });
                
                Log.d(TAG, "任务完成: " + task.getTaskId());
                
            } catch (InterruptedException e) {
                // 处理失败
                task.setStatus(TaskStatus.Status.FAILED);
                task.setDescription("处理失败，请重试");
                task.setErrorMessage("网络连接中断");
                
                mainHandler.post(() -> {
                    for (TaskStatusListener listener : listeners) {
                        listener.onTaskFailed(task);
                    }
                });
                
                Log.e(TAG, "任务失败: " + task.getTaskId());
            }
        }).start();
    }
    
    private void updateTask(TaskStatus task) {
        mainHandler.post(() -> {
            for (TaskStatusListener listener : listeners) {
                listener.onTaskUpdated(task);
            }
        });
    }
    
    public List<TaskStatus> getAllTasks() {
        return new ArrayList<>(tasks);
    }
    
    public List<TaskStatus> getTasksByStatus(TaskStatus.Status status) {
        List<TaskStatus> filteredTasks = new ArrayList<>();
        for (TaskStatus task : tasks) {
            if (task.getStatus() == status) {
                filteredTasks.add(task);
            }
        }
        return filteredTasks;
    }
    
    public TaskStatus getTaskById(String taskId) {
        for (TaskStatus task : tasks) {
            if (task.getTaskId().equals(taskId)) {
                return task;
            }
        }
        return null;
    }
    
    public void deleteTask(String taskId) {
        TaskStatus taskToRemove = null;
        for (TaskStatus task : tasks) {
            if (task.getTaskId().equals(taskId)) {
                taskToRemove = task;
                break;
            }
        }
        
        if (taskToRemove != null) {
            tasks.remove(taskToRemove);
            Log.d(TAG, "删除任务: " + taskId);
        }
    }
    
    public int getProcessingTaskCount() {
        int count = 0;
        for (TaskStatus task : tasks) {
            if (task.getStatus() == TaskStatus.Status.PROCESSING || 
                task.getStatus() == TaskStatus.Status.PENDING) {
                count++;
            }
        }
        return count;
    }
    
    public void clearCompletedTasks() {
        List<TaskStatus> toRemove = new ArrayList<>();
        for (TaskStatus task : tasks) {
            if (task.getStatus() == TaskStatus.Status.COMPLETED) {
                toRemove.add(task);
            }
        }
        tasks.removeAll(toRemove);
    }
}
